package com.sptpc.demo1.service.impl;

import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.model.Order;
import com.sptpc.demo1.repository.DrinkRepository;
import com.sptpc.demo1.repository.OrderRepository;
import com.sptpc.demo1.service.IOrderService;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.List;

public class OrderJpaService implements IOrderService {
    @Autowired
    private DrinkRepository drinkRepository;
    @Autowired
    private OrderRepository orderRepository;

    @Override
    public void addOrder(Order order, List<Integer> items){
        order.setState(0);
        List<Drink> drinks = drinkRepository.findAllById(items);
        order.setItems(drinks);
//        BigDecimal sum=BigDecimal.ZERO;
//        for (Drink drink : drinks){
//            sum = sum.add(drink.getPrice().getAmount());
//        }
        BigDecimal priceNum=drinks.stream()
                .map(d -> d.getPrice().getAmount())
                .reduce(BigDecimal.ZERO,(p1,p2) -> p1.add(p2));
        Order.setPrice(Money.of(CurrencyUnit.of("CNY"),priceNum));

        OrderRepository.save(order);
    }
}
